package mao.mashibing.juc.jucutil;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/*
user：mao
data：2020/11/22
explain：
*/
public class TestReadWriteLock {
     static ReadWriteLock rwl = new ReentrantReadWriteLock();
     static Lock rl= rwl.readLock();
     static Lock wl= rwl.writeLock();

     public static void read(Lock lock){
         try{
             lock.lock();
             System.out.println("开始读");
             TimeUnit.SECONDS.sleep(1);
             System.out.println("读取结束");
         }catch (InterruptedException e){
             e.printStackTrace();
         }finally {
             lock.unlock();
         }
     }

    public static void write(Lock lock){
        try{
            lock.lock();
            System.out.println("开始写");
            TimeUnit.SECONDS.sleep(1);
            System.out.println("写结束");
        }catch (InterruptedException e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        for (int i = 0; i < 18; i++) {
            new Thread(()->read(rl)).start();
        }
        new Thread(()->write(wl)).start();
        new Thread(()->write(wl)).start();
    }
}
